from warnings import catch_warnings

import logger
from flask import Flask, render_template, url_for, flash, redirect, request, jsonify,session
from pyexpat.errors import messages
from Blueprint import student,admin,teacher
from   Models import *
from flask_migrate import Migrate

app = Flask(__name__)
database_name='manage_student'
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://root:123456@localhost:3306/{database_name}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 进行对象的绑定
db.init_app(app)
# 进行数据库的迁移
migrate = Migrate(app, db)
app.secret_key = 'your-secret-key-here'  # 请替换为一个随机且安全的字符串

# 为蓝图进行注册
app.register_blueprint(student.student_bp,url_prefix='/student')
app.register_blueprint(admin.admin_bp,url_prefix='/admin')
app.register_blueprint(teacher.teacher_bp,url_prefix='/teacher')



@app.route('/login',methods=['GET','POST'])
def login():  # put application's code here
      return render_template('login.html')
@app.route('/register',methods=['GET','POST'])
def register():
    return render_template('register.html')
@app.route('/register/check', methods=['POST'])
def register_check():
    data = request.get_json()
    username = data.get('username')
    studentId = data.get('studentId')
    password = data.get('password')
    role = data.get('role')
    if not role:
        return jsonify({"message": "请选择角色"}), 400

    if role == "admin":
        if not all([username, studentId, password]):
            return jsonify({"message": "请填写管理员的所有必填字段"}), 400
        existing_admin = Admin.query.filter_by(username=username).first()
        if existing_admin:
            return jsonify({"message": "管理员账号已存在"}), 400
        new_admin = Admin(
            username=username,
            admin_no=studentId,
            password=password  # 直接使用明文密码
        )
        db.session.add(new_admin)
        db.session.commit()

        return jsonify({"message": "管理员注册成功"}), 201

    elif role == "student":
        existing_name = Student.query.filter_by(username=username).first()
        if existing_name:
            return jsonify({"message": "学生账号已存在"}), 400
        new_student = Student(
            username=username,
            student_no=studentId,
            password=password,  # 直接使用明文密码
        )

        db.session.add(new_student)
        db.session.commit()
        return jsonify({"message": "学生账号成功"}), 201

    elif role == "teacher":
        existing_name = Teacher.query.filter_by(username=username).first()
        if existing_name:
            return jsonify({"message": "教师账号已存在"}), 400
        new_teacher = Teacher(
            username=username,
            teacher_no=studentId,
            password=password,  # 直接使用明文密码
        )
        db.session.add(new_teacher)
        db.session.commit()

        return jsonify({"message": "教师注册成功"}), 201
    return jsonify({"message": "无效的角色类型"}), 400

@app.route('/login/check', methods=['POST'])
def login_check():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"message": "请求数据格式错误"}), 400

        username = data.get('username')
        password = data.get('password')
        studentId = data.get('studentId')

        # 检查必填字段
        if not all([username, password, studentId]):
            return jsonify({"message": "请填写所有字段"}), 400

        # 检查学生表
        student = Student.query.filter_by(username=username, student_no=studentId, password=password).first()
        if student:
            session['user_type'] = 'student'
            session['username'] = username
            session['studentId'] = studentId
            return jsonify({"message": "学生登录成功", "url": url_for('student.student_index')}), 200
        # 检查教师表
        teacher = Teacher.query.filter_by(username=username, teacher_no=studentId, password=password).first()
        if teacher:
            session['user_type'] = 'teacher'
            session['username'] = username
            session['studentId'] = studentId
            return jsonify({"message": "教师登录成功", "url": url_for('teacher.teacher_index')}), 200
        # 检查管理员表
        admin = Admin.query.filter_by(username=username, admin_no=studentId, password=password).first()
        if admin:
            session['user_type'] = 'admin'
            session['username'] = username
            session['studentId'] = studentId
            return jsonify({"message": "管理员登录成功", "url": url_for('admin.manage_student')}), 200

        return jsonify({"message": "用户名、学工号或密码错误"}), 400

    except Exception as e:
        logger.error(f"登录接口错误: {str(e)}", exc_info=True)
        return jsonify({"message": "服务器内部错误，请稍后再试"}), 500



@app.route('/')
def index():
    return redirect(url_for('login'))







if __name__ == '__main__':
    app.run()
